package com.ruoyi.khpx.handler;

import com.ruoyi.khpx.service.DeepSeekService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;

@Component
@RequiredArgsConstructor
public class ChatWebSocketHandler extends TextWebSocketHandler {
    
    private final DeepSeekService deepSeekService;
    private static final Logger log = LoggerFactory.getLogger(ChatWebSocketHandler.class);

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        String question = message.getPayload();
        log.info("收到WebSocket消息: {}", question);
        
        deepSeekService.handleChatWebSocket(question)
            .subscribe(
                response -> {
                    try {
                        if (session.isOpen()) {
                            session.sendMessage(new TextMessage(response));
                        }
                    } catch (Exception e) {
                        log.error("发送消息失败: {}", e.getMessage());
                    }
                },
                error -> {
                    try {
                        if (session.isOpen()) {
                            session.sendMessage(new TextMessage("Error: " + error.getMessage()));
                        }
                    } catch (Exception e) {
                        log.error("发送错误消息失败: {}", e.getMessage());
                    }
                }
            );
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("WebSocket连接已建立: {}", session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        log.info("WebSocket连接已关闭: {}, 状态: {}", session.getId(), status);
    }
} 